from django.shortcuts import render

# Create your views here.
import json

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django_redis import get_redis_connection
from apps.goods.models import SKU
from apps.order.models import OrderInfo
from apps.users.models import Address
from django.views import View
from utils.users import LoginRequiredJSONMixin

# #############################3订单结算
# class OrderSubmitView(LoginRequiredJSONMixin,View):
#
#     def get(self,request):
#         #获取用户数据
#         user = request.user
#
#         #获取用户地址信息
#         addresses = Address.objects.filter(user=user,is_deleted=False)
#         addresses_list = []
#         #将对象列表转换为字典列表
#         for address in addresses:
#             addresses_list.append({
#                 'id': address.id,
#                 'province': address.province.name,
#                 'city': address.city.name,
#                 'district': address.district.name,
#                 'place': address.place,
#                 'receiver': address.receiver,
#                 'mobile': address.mobile
#             })
#
#         #获取购物车中商品信息，获取set 选种商品的id
#         redis_cli = get_redis_connection('carts')
#         selected = redis_cli.smembers('selected_%s'%user.id)
#         sku_id_counts = redis_cli.hgetall('carts_%s'%user.id) # 所有商品的id 和数量{id:count} {1:2,3:4}  b
#         #将对象列表转换为字典列表
#         selected_carts = []
#         for id in selected:
#             #     2.5 查询商品信息
#             sku = SKU.objects.get(id = id)
#             selected_carts.append({
#                     'id': sku.id,
#                     'name': sku.name,
#                     'default_image_url': sku.default_image.url,
#                     'count': int(sku_id_counts[id]),  # 选中的数量 记得转换类型
#                     'price': sku.price
#                     # 'amount': sku.price*int(sku_id_counts[id])          # 一个商品的小计  单价*数量
#             })
#             #运费
#         freight = 10
#         #组织数据返回响应
#         context = {
#             'addresses': addresses_list,
#             'skus': selected_carts,
#             'freight': freight
#         }
#
#         return JsonResponse({'code': 0, 'errmsg': 'ok', 'context': context})
#
# ###############################################保存订单
# from apps.order.models import OrderInfo,OrderGoods
# from django.db import transaction
# class OrdercommitView(LoginRequiredJSONMixin,View):
#
#     def post(self,request):
#
#         #登录用户
#         user = request.user
#         #user = request.user
#
#         #1,接收数据
#         data = json.loads(request.body.decode())
#         #data = json.loads(request.body.decode())
#         #2,提取数据
#         addressed_id = data.get('address_id')
#         #addressed_id = data.get('address_id)
#         pay_method = data.get('pay_method')
#         #pay_method = data.get(pay_method)
#
#         #验证数据
#         try:
#             address = Address.objects.get(id = addressed_id)
#             #address = Address.odjects.get(id = addressed_id)
#         except Address.DoesNotExist:
#             return JsonResponse({'code':400,'errmsg':'没有此地址'})
#
#         if pay_method not in[OrderInfo.PAY_METHODS_ENUM['CASH'],OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
#             return JsonResponse({'code': 400, 'errmsg': '支付方式错误'})
#
#         #4.数据入库
#         #日期
#         from datetime import datetime
#         from django.utils import timezone
#         #from django.utils import timezone
#         # Y  Year
#         # m  month
#         # d  day
#         # H  Hour
#         # M  Minute
#         # S  Second
#         # f  微秒
#         order_id = timezone.now().strftime('%Y%m%d%H%M%S%f') + '%09d'%user.id
#         #order_id = timezone.now().strftime('%y%m%d%h%m%s%f) + %09d%user.id
#
#         #总金额和总数量先即为0
#         total_count = 0
#         #total_count = 0
#         from decimal import Decimal
#         # 货币类型
#         total_amount = Decimal('0')
#
#         #1.运费
#         freight = 10
#
#         #订单状态 #有支付方式决定
#         if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
#             status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
#
#         else:
#             status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']
#
#         #事务
#         with transaction.atomic():
#
#             #事物开始点      事无 保证 订单信息和商品信息都运行成功保存信息
#             start_point = transaction.savepoint()
#
#
#             order = OrderInfo.objects.create(
#                 order_id=order_id,
#                 user=user,
#                 address=address,
#                 total_count=total_count,
#                 total_amount=total_amount,
#                 freight=freight,
#                 pay_method=pay_method,
#                 status=status
#             )
#             ###########################保存订单商品信息
#             #保存订单商品信息
#             redis_cli = get_redis_connection('carts')
#             #获取hash数据                       {id：count} bytes
#             sku_id_counts = redis_cli.hgetall('carts_%s'%user.id)
#             #获取set {id,id}   bytes
#             selected_ids = redis_cli.smembers('selected_%s'%user.id)
#
#             #整理，选中字典
#             new_selected_ids = {}   #{id:count}
#             for id in selected_ids:
#                 new_selected_ids[int(id)] = int(sku_id_counts[id])  #int(sku_id_counts[id])   获取id 对应的count
#
#             #遍历
#             for sku_id,cart_count in new_selected_ids.items(): #items 所有键值对
#                 #         2.4 根据商品id查询商品信息
#                 sku = SKU.objects.get(id = sku_id)
#
#                 #         2.5 判断商品库存.如果库存不足,下单失败
#                 if cart_count > sku.stock:
#                     # 二，事务的回滚
#
#
#                     transaction.savepoint_rollback(start_point)
#
#                     return JsonResponse({'code': 400, 'errmsg': '库存不足,请稍后再试'})
#                 from time import sleep
#                 sleep(7)
#                 # sku.stock -= cart_count
#                 # sku.sales += cart_count
#                 # sku.save()
#
#                 #乐观锁 多个用户同时购买同一商品，
#                 old_stock = sku.stock    #  用户买的时候商品库存
#
#                 new_stock = sku.stock - cart_count  # 库存-购买数
#                 new_sales = sku.sales + cart_count  #销售量 + 购买数
#
#                 result = SKU.objects.filter(id = id,stock = old_stock).update(
#                     stock = new_stock,sales = new_sales             # sku 模型里 stock 已经改变， <  用户商品购买时不同返回0
#                 )
#
#                 if request == 0:
#                     transaction.savepoint_rollback(start_point)
#                     return JsonResponse({'code':400,'errmsg':'库存不足，下单失败'})
#
#
#
#                 #统计总数量和金额
#
#                 order.total_count += cart_count
#                 order.total_amount = (cart_count * sku.price)
#
#
#                 #保存订单信息
#                 OrderGoods.objects.create(
#                     order=order,
#                     sku=sku,
#                     count=cart_count,
#                     price=sku.price
#                 )
#                 #修改总数量和总金额
#             order.save()
#
#
#             #三 ，事务提交
#
#             transaction.savepoint_commit(start_point)
#
#
#             return JsonResponse({'code':0,'errmsg':'ok'})

###################订单结算
class OrderSubmitView(LoginRequiredJSONMixin,View):

    def get(self,request):

        user = request.user

        addressed = Address.objects.filter(user = user,is_deleted=False)

        addressed_list = []

        for address in addressed:

            addressed_list.append({
                'id':address.id,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'receiver': address.receiver,
                'mobile': address.mobile
            })

        redis_cli = get_redis_connection('carts')

        sku_id_counts = redis_cli.hgetall('carts_%s'%user.id)
        selected = redis_cli.smembers('selected_%s'%user.id)

        selected_carts = []

        for id in selected:
            sku =SKU.objects.get(id = id)
            selected_carts.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'count': int(sku_id_counts[id]),  # 选中的数量 记得转换类型
                'price': sku.price
            })

        freight =10
        context = {
            'addresses' : addressed_list,
            'skus': selected_carts,
            'freight' : freight

        }

        return JsonResponse({'code':0,'errmsg':'ok','context' : context})


##############################################订单保存
from apps.order.models import OrderInfo, OrderGoods
from django.db import transaction
class OrdercommitView(LoginRequiredJSONMixin,View):
    def post(self,request):
        user = request.user
        data = json.loads(request.body.decode())

        address = data.get('address_id')
        pay_method = data.get('pay_method')

        try:
            addressed = Address.objects.get(id = address)
        except Address.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此地址'})

        if pay_method not in[OrderInfo.PAY_METHODS_ENUM['CASH'],OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return JsonResponse({'code':400,'errmsg':'支付方式错误'})


        from django.utils import timezone
        order_id = timezone.now().strftime('%Y%m%d%H%M%S%f') + '09d%s'%user.id

        total_count = 0
        from decimal import Decimal
        total_amout = Decimal('0')

        freight = 10

        if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:
            stauts = OrderInfo.ORDER_STATUS_ENUM["UNSEND"]

        else:
            stauts = OrderInfo.ORDER_STATUS_ENUM["UNPAID"]

        with transaction.atomic():

            start_point = transaction.savepoint()

            order = OrderInfo.objects.create(
                order_id=order_id,
                user =user,
                address= addressed,
                total_count= total_count,
                total_amount=total_amout,
                freight=freight,
                pay_method=pay_method,
                status=stauts
            )

            ################################保存商品信息
            redis_cli = get_redis_connection('carts')
            sku_id_counts = redis_cli.hgetall('carts_%s'%user.id)
            selected = redis_cli.smembers('selected_%s'%user.id)

            str_id_count = {}

            for id in selected:
                str_id_count[int(id)] = int(sku_id_counts[id])

            for sku_id,counts in str_id_count.items():
                sku = SKU.objects.get(id = sku_id)

                if counts > sku.stock:
                    return JsonResponse({'code':400,'errmsg':'库存不足'})

                sku.stock -= counts
                sku.sales += counts

                sku.save()

                order.total_count += counts
                order.total_amount += (counts * sku.price)

                OrderGoods.objects.create(
                    order=order,
                    sku=sku,
                    count=counts,
                    price=sku.price
                )

            order.save()

            return JsonResponse({'code':0,'errmsg':'ok','order_id':order_id})









